<?php
class RatingsController extends AppController {

	var $name = 'Ratings';
	var $helpers = array('Html', 'Form', 'Javascript');

	function add($type, $item_id, $rating)
	{
		Configure::write('debug','0');
		$this->layout = 'ajax';
		
		$newRating = array();
		$newRating['type'] = $type;
		$newRating['item_id'] = $item_id;
		$newRating['rating'] = $rating;
		$authedUser = $this->Session->read('Auth.User');
		$save = false;
		// check if guest rate are allowed
		if(Configure::read('Rating.allowGuests')==false)
		{
			if(!$authedUser)
			{
				$this->errorMsg(__('Please sign in to continue.'));
				$this->render();
				
			}
			//check if rate once
			else if(Configure::read('Rating.allowOnce')==True && $this->Rating->find('count',array('conditions'=>array('user_id'=>$authedUser['id'],'item_id'=>$item_id, 'type'=>$type)))>0)
			{
					$this->errorMsg(sprintf(__('You have already rated this %s'),$type));
					$this->render();
			}else
			{
				$save =true;
				$newRating['user_id'] = $authedUser['id'];	
			}
			
		}
		else 
		{
			$newRating['ip'] = Utility::getClientIp();
			$save= true;
		}
		callHooks('beforeRatingAdd',null,$this);
		if(isset($this->saveRating))
			$save = $this->saveRating;
		if($save==true)
		{
			$this->Rating->create();
			$this->Rating->save($newRating);
			$this->successMsg(__('Thank you for rating!'));
		}
	}
}
?>